
package com.jims.master.modules.doctor.service;

import com.jims.master.common.config.Global;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.*;
import com.jims.master.modules.doctor.entity.*;
import com.jims.master.modules.drug.dao.DrugStockDao;
import com.jims.master.modules.drug.dao.DrugStorageDeptDao;
import com.jims.master.modules.drug.entity.DrugStock;
import com.jims.master.modules.finance.dao.InpBillDetailDao;
import com.jims.master.modules.finance.dao.OutpRcptMasterDao;
import com.jims.master.modules.finance.entity.InpBillDetail;
import com.jims.master.modules.finance.entity.OutpRcptMaster;
import com.jims.master.modules.oper.dao.PriceListDao;
import com.jims.master.modules.oper.entity.PriceList;
import com.jims.master.modules.orders.dao.OrdersDao;
import com.jims.master.modules.orders.entity.Orders;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.template.dao.DoctorTemplaDao;
import com.jims.master.modules.template.dao.TreatProjectItemDao;
import com.jims.master.modules.template.entity.DoctorTempla;
import com.jims.master.modules.template.entity.TreatProjectItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门诊处方主表Service
 * @author CTQ
 * @version 2017-03-13
 */
@Service
@Transactional(readOnly = true)
public class PrescriptionApplyService extends CrudService<PrescriptionApplyDao, PrescriptionApply> {
    @Autowired
    private PrescriptionApplyDao prescriptionApplyDao;
    @Autowired
	private PrescriptionItemDao prescriptionItemDao;
	@Autowired
	private ClinicOrdersDao clinicOrdersDao;
	@Autowired
	private ClinicOrdersCostService clinicOrdersCostService;
    @Autowired
    private DrugStockDao drugStockDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private PatVisitDao patVisitDao;
    @Autowired
    private PriceListDao priceListDao;
    @Autowired
    private InpBillDetailDao inpBillDetailDao;
    @Autowired
    private OutpRcptMasterDao outpRcptMasterDao;
    @Autowired
    private OrgDeptDao orgDeptDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ClinicMasterDao clinicMasterDao;
    @Autowired
    private HisDiagnosisDao hisDiagnosisDao;
    @Autowired
    private DrugStorageDeptDao drugStorageDeptDao;
    @Autowired
    private DoctorTemplaDao doctorTemplaDao;
    @Autowired
    private TreatProjectItemDao treatProjectItemDao;


	public PrescriptionApply get(String id) {
		return super.get(id);
	}
	
	public List<PrescriptionApply> findAllList(PrescriptionApply prescriptionApply) {
		return dao.findAllList(prescriptionApply);
	}
	
	public Page<PrescriptionApply> findPage(Page<PrescriptionApply> page, PrescriptionApply prescriptionApply) {
		return super.findPage(page, prescriptionApply);
	}
	
	@Transactional(readOnly = false)
	public int save(PrescriptionApply prescriptionApply) {
        prescriptionApply.setBillingDept((UserUtils.getUser()!=null&&UserUtils.getUser().getOrgDept()!=null)?UserUtils.getUser().getOrgDept().getId():"");
        prescriptionApply.setImplDept(prescriptionApply.getImplementDept()!=null?prescriptionApply.getImplementDept():"");
		prescriptionApply.preInsert();
        prescriptionApply.setOrdersId("");
		prescriptionApply.updateOrgId();
		return dao.insert(prescriptionApply);
	}

    /**
     * 删除处方
     * @param prescriptionApply
     * @return
     */
	@Transactional(readOnly = false)
	public int remove(PrescriptionApply prescriptionApply) {
		int num = 0;
        if("0".equals(prescriptionApply.getInoroutFlag())){
            /**1.根据处方ID查询是否有医嘱**/
            if (StringUtils.isNotBlank(prescriptionApply.getOrdersId())){
                /**2.删除医嘱明细表数据**/
                clinicOrdersCostService.delByOrderId(prescriptionApply.getOrdersId());
                /**3.删除医嘱主记录**/
                clinicOrdersDao.delete(new ClinicOrders(prescriptionApply.getOrdersId()));
            }
        } else {
            if(StringUtils.isNotBlank(prescriptionApply.getOrdersId())){
                ordersDao.deletePreAndOrder(prescriptionApply.getOrdersId());
            }
        }
        /**5.删除处方明细**/
        prescriptionItemDao.delByApplyId(prescriptionApply.getId());
		/**6.删除处方**/
		num = dao.delete(prescriptionApply);
		return num;
	}

	/**
	 * 门诊处方退药
	 * @param prescriptionApply
	 * @return
	 * @author CTQ
	 */
	@Transactional(readOnly = false)
	public int drugBack(PrescriptionApply prescriptionApply) {
		int num = 0;

		return num;
	}

    /**
     * 门诊处方待发药list
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    public Page<PrescriptionApply> findByClinicPage(Page<PrescriptionApply> page, PrescriptionApply prescriptionApply) {
        prescriptionApply.updateOrgId();
        prescriptionApply.setPage(page);
        prescriptionApply.setImplementDept(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        page.setList(dao.findByClinicPage(prescriptionApply));
        return page;
    }

    /**
     * 门诊处方已发药list
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    public Page<PrescriptionApply> findDrugOutClinicPage(Page<PrescriptionApply> page, PrescriptionApply prescriptionApply) {
        prescriptionApply.updateOrgId();
        prescriptionApply.setPage(page);
        prescriptionApply.setConfirmFlag("1");  //已发药
        prescriptionApply.setImplementDept(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        page.setList(dao.findByClinicPage(prescriptionApply));
        return page;
    }


    /**
     * 住院处方待发药list
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    public Page<PrescriptionApply> findByInpPage(Page<PrescriptionApply> page, PrescriptionApply prescriptionApply) {
        prescriptionApply.updateOrgId();
        prescriptionApply.setPage(page);
        prescriptionApply.setImplementDept(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        page.setList(dao.findByInpPage(prescriptionApply));
        return page;
    }

    /**
     * 住院处方已发药list
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    public Page<PrescriptionApply> findDrugOutInpPage(Page<PrescriptionApply> page, PrescriptionApply prescriptionApply) {
        prescriptionApply.updateOrgId();
        prescriptionApply.setPage(page);
        prescriptionApply.setConfirmFlag("1");  //已发药
        prescriptionApply.setImplementDept(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        page.setList(dao.findByInpPage(prescriptionApply));
        return page;
    }

    /**
     * 手术待发药list
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    public Page<PrescriptionApply> findByOperationPage(Page<PrescriptionApply> page, PrescriptionApply prescriptionApply) {
        prescriptionApply.updateOrgId();
        prescriptionApply.setPage(page);
        prescriptionApply.setInoroutFlag("2"); //手术
        prescriptionApply.setConfirmFlag("0");  //未发药
        prescriptionApply.setBillingDept(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        page.setList(dao.findByInpPage(prescriptionApply));
        return page;
    }

    /**
     * 门诊处方发药
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    @Transactional(readOnly = false)
    public String clinicDrugOut(PrescriptionApply prescriptionApply){
        int num=1;
        //定义库存量不够的药品名称
        String drugName="";

        //根据prescriptionApply的Id获取要扣的库存list
        List<DrugStock> drugOutList=drugStockDao.findByApplyId(prescriptionApply.getId());

        for(int i=0;i<drugOutList.size();i++){
            //判断药房库存量是否够发药
            List <DrugStock> drugStockQuantity = drugStockDao.findByQuantity(drugOutList.get(i));
            if(drugStockQuantity.size()>0 && drugStockQuantity.get(0).getQuantity()< drugOutList.get(i).getQuantity() ){
                drugName=drugStockQuantity.get(0).getDrugName();
                return drugName;
            }
        }

        for(int i=0;i<drugOutList.size();i++){
            List<DrugStock> listByExpireDate = drugStockDao.findByExpireDate(drugOutList.get(i));
            //药库需要扣的数量
            Double quantityOut=drugOutList.get(i).getQuantity();
            for(int j=0;j<listByExpireDate.size();j++){
                DrugStock drugStock1=listByExpireDate.get(j);
                if(quantityOut>listByExpireDate.get(j).getQuantity() && quantityOut>0){
                    drugStock1.setQuantity(0.00);
                    drugStock1.preUpdate();
                    num=num*drugStockDao.update(drugStock1);
                    quantityOut=quantityOut-listByExpireDate.get(j).getQuantity();
                }else if(quantityOut <= listByExpireDate.get(j).getQuantity() && quantityOut>0 ) {
                    drugStock1.setQuantity(listByExpireDate.get(j).getQuantity()-quantityOut);
                    quantityOut=0.0;
                    drugStock1.preUpdate();
                    num=num*drugStockDao.update(drugStock1);
                }
            }
        }

        //修改prescriptionApply的发药状态
        PrescriptionApply prescriptionApplyNew=dao.get(prescriptionApply.getId());
        prescriptionApplyNew.updateOrgId();
        prescriptionApplyNew.setConfirmFlag("1");
        prescriptionApplyNew.setImplDept(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        prescriptionApplyNew.setImplUser(null != UserUtils.getUser().getId() ? UserUtils.getUser().getId() : "");
        prescriptionApplyNew.setOutDate(new Date());
        prescriptionApplyNew.preUpdate();
        num=num*dao.update(prescriptionApplyNew);

        //clinicOrders表修改执行人，执行科室
        ClinicOrders clinicOrders=new ClinicOrders();
        clinicOrders=clinicOrdersDao.get(prescriptionApplyNew.getOrdersId());
        clinicOrders.setImplementDept(prescriptionApplyNew.getImplDept());
        clinicOrders.setImplementUser(prescriptionApplyNew.getImplUser());
        clinicOrders.preUpdate();
        num=num*clinicOrdersDao.update(clinicOrders);

        return num+"";
    }

    /**
     * 门诊处方退药
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    @Transactional(readOnly = false)
    public String clinicDrugIn(PrescriptionApply prescriptionApply){
        int num=1;

        //根据prescriptionApply的Id获取要退的库存list
        List<DrugStock> drugOutList=drugStockDao.findByApplyId(prescriptionApply.getId());

        for(int i=0;i<drugOutList.size();i++){
            List<DrugStock> listByExpireDate = drugStockDao.findByExpireDate(drugOutList.get(i));
            //药库需要加的数量：加到保质期最近的一批药上，以便下次发药时先出
            Double quantityOut=drugOutList.get(i).getQuantity();
            DrugStock drugStock1=listByExpireDate.get(0);
            drugStock1.setQuantity(drugStock1.getQuantity()+ quantityOut );
            drugStock1.preUpdate();
            num=num*drugStockDao.update(drugStock1);
        }

        //修改prescriptionApply的发药状态
        PrescriptionApply prescriptionApplyNew=dao.get(prescriptionApply.getId());
        prescriptionApplyNew.updateOrgId();
        prescriptionApplyNew.setConfirmFlag("2");
        prescriptionApplyNew.setChargeFlag("3");
        prescriptionApplyNew.setOutDate(new Date());
        prescriptionApplyNew.preUpdate();
        num=num*dao.update(prescriptionApplyNew);

        //clinicOrders表修改状态
        ClinicOrders clinicOrders=new ClinicOrders();
        clinicOrders=clinicOrdersDao.get(prescriptionApplyNew.getOrdersId());
        clinicOrders.setChargeFlag("3");
        clinicOrders.preUpdate();
        num=num*clinicOrdersDao.update(clinicOrders);

        //outpRcptMaster表修改状态
        OutpRcptMaster outpRcptMaster=new OutpRcptMaster();
        outpRcptMaster.setRcptNo(clinicOrders.getRcptNo());
        outpRcptMaster.updateOrgId();
        outpRcptMaster=outpRcptMasterDao.findByRcptNo(outpRcptMaster);
        outpRcptMaster.setChargeIndicator("3");
        outpRcptMaster.preUpdate();
        num=num*outpRcptMasterDao.update(outpRcptMaster);
        return num+"";
    }

    /**
     * 住院处方发药
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    @Transactional(readOnly = false)
    public String inpDrugOut(PrescriptionApply prescriptionApply){
        int num=1;
        //定义库存量不够的药品名称
        String drugName="";

        //根据prescriptionApply的Id获取要扣的库存list
        List<DrugStock> drugOutList=drugStockDao.findByApplyId(prescriptionApply.getId());

        for(int i=0;i<drugOutList.size();i++){
            //判断药房库存量是否够发药
            List <DrugStock> drugStockQuantity = drugStockDao.findByQuantity(drugOutList.get(i));
            if(drugStockQuantity.size()>0 && drugStockQuantity.get(0).getQuantity()< drugOutList.get(i).getQuantity() ){
                drugName=drugStockQuantity.get(0).getDrugName();
                return drugName;
            }
        }
        //修改prescriptionApply的发药状态
        PrescriptionApply prescriptionApplyNew=dao.get(prescriptionApply.getId());
        prescriptionApplyNew.updateOrgId();
        prescriptionApplyNew.setConfirmFlag("1");//已发药
        prescriptionApplyNew.setImplDept(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        prescriptionApplyNew.setImplUser(null != UserUtils.getUser().getId() ? UserUtils.getUser().getId() : "");
        prescriptionApplyNew.setOutDate(new Date());
        prescriptionApplyNew.preUpdate();

        //准备要插入的inpBillDetail数据
        InpBillDetail inpBillDetail=new InpBillDetail();
        inpBillDetail.updateOrgId();
        inpBillDetail.setOrderDept(prescriptionApplyNew.getBillingDept());//开单科室
        inpBillDetail.setOrderDoctor(prescriptionApplyNew.getCreateBy().getId());//开单医生
        inpBillDetail.setPatientId(prescriptionApplyNew.getPatientId());		// 病人ID
        inpBillDetail.setVisitId(prescriptionApplyNew.getVisitId());		    // 住院ID
        inpBillDetail.setStorageId(prescriptionApplyNew.getImplementDept());    //发药药房
        inpBillDetail.setPerformDept(prescriptionApplyNew.getImplDept());		// 执行科室(护理单元)
        inpBillDetail.setPerformPerson(prescriptionApplyNew.getImplUser());		// 执行人
        PatVisit patVisit=new PatVisit();
        patVisit=patVisitDao.get(prescriptionApplyNew.getVisitId());
        inpBillDetail.setDeptStayed(patVisit.getDeptStayed());			// 所在科室
        inpBillDetail.setWardCode(patVisit.getWardCode());		// 所在病区
        inpBillDetail.setRemarks(prescriptionApply.getId());    //保存上处方主表的id以防万一

        for(int i=0;i<drugOutList.size();i++){
            PriceList priceList=priceListDao.get(drugOutList.get(i).getRemarks()); //drugOutList remakes字段暂取的是drugPriceId
            inpBillDetail.setItemClass(priceList.getItemClass());		// 项目类型
            inpBillDetail.setItemName(priceList.getItemName());		// 项目名称
            inpBillDetail.setItemCode(priceList.getItemCode());
            inpBillDetail.setItemSpec(priceList.getItemSpec());		// 项目规格
            inpBillDetail.setPriceId(priceList.getId());            //价格id
            inpBillDetail.setAmount(String.valueOf(drugOutList.get(i).getQuantity()));		// 数量
            inpBillDetail.setUnits(priceList.getUnits());		// 单位
            inpBillDetail.setItemPrice(priceList.getPrice());		// 单价
            inpBillDetail.setCosts(priceList.getPrice() * drugOutList.get(i).getQuantity());		// 应付费用
            inpBillDetail.setCharges(priceList.getPrice() * drugOutList.get(i).getQuantity());		// 实收费用
            inpBillDetail.setPriceQuotiety("1");		// 收费系数
            inpBillDetail.setClassOnReckoning(priceList.getClassOnReckoning());		// 核算项目分类
            inpBillDetail.setSubjCode(priceList.getSubjCode());		// 会计科目
            inpBillDetail.setClassOnMr(priceList.getClassOnMr());		// 病案首页分类
            inpBillDetail.setPrescriptionId(drugOutList.get(i).getFirmName()); //处方详情表id,暂存为FirmName带过来
            inpBillDetail.preInsert();

            List<DrugStock> listByExpireDate = drugStockDao.findByExpireDate(drugOutList.get(i));
            //药库需要扣的数量
            Double quantityOut=drugOutList.get(i).getQuantity();
            for(int j=0;j<listByExpireDate.size();j++){
                DrugStock drugStock1=listByExpireDate.get(j);
                if(quantityOut>listByExpireDate.get(j).getQuantity() && quantityOut>0){
                    drugStock1.setQuantity(0.00);
                    drugStock1.preUpdate();
                    num=num*drugStockDao.update(drugStock1);
                    quantityOut=quantityOut-listByExpireDate.get(j).getQuantity();
                }else if(quantityOut <= listByExpireDate.get(j).getQuantity() && quantityOut>0 ) {
                    drugStock1.setQuantity(listByExpireDate.get(j).getQuantity()-quantityOut);
                    quantityOut=0.0;
                    drugStock1.preUpdate();
                    num=num*drugStockDao.update(drugStock1);
                }
            }
            num=num*inpBillDetailDao.insert(inpBillDetail); //扣完库存插入inpBillDetail
        }
        num=num*dao.update(prescriptionApplyNew); //扣完库存修改prescriptionApply
        return num+"";
    }


    /**
     * 住院处方退药
     * @param prescriptionApply
     * @return
     * @author ZhuQ
     */
    @Transactional(readOnly = false)
    public String inpDrugIn(PrescriptionApply prescriptionApply){
        int num=1;

        //根据prescriptionApply的Id获取要退的库存list
        List<DrugStock> drugOutList=drugStockDao.findByApplyBill(prescriptionApply.getId());

        for(int i=0;i<drugOutList.size();i++){
            List<DrugStock> listByExpireDate = drugStockDao.findByExpireDate(drugOutList.get(i));
            //药库需要加的数量：加到保质期最近的一批药上，以便下次发药时先出
            Double quantityOut=drugOutList.get(i).getQuantity();
            DrugStock drugStock1=listByExpireDate.get(0);
            drugStock1.setQuantity(drugStock1.getQuantity()+ quantityOut );
            drugStock1.preUpdate();
            num=num*drugStockDao.update(drugStock1);



            //inp_bill_detail表修改状态
            InpBillDetail inpBillDetail=new InpBillDetail();
            inpBillDetail=inpBillDetailDao.get(drugOutList.get(i).getReceiver());
            inpBillDetail.setAmount(String.valueOf(-1 * Double.valueOf(inpBillDetail.getAmount())));
            inpBillDetail.setCosts((-1) * inpBillDetail.getCosts());
            inpBillDetail.setCharges((-1) * inpBillDetail.getCharges());
            inpBillDetail.setId("---" + inpBillDetail.getId());
            inpBillDetail.preUpdate();
            num=num*inpBillDetailDao.insert(inpBillDetail);

        }
        //修改prescriptionApply的发药状态
        PrescriptionApply prescriptionApplyNew=dao.get(drugOutList.get(0).getId());
        prescriptionApplyNew.updateOrgId();
        prescriptionApplyNew.setConfirmFlag("2");
        prescriptionApplyNew.setChargeFlag("3");
        prescriptionApplyNew.setOutDate(new Date());
        prescriptionApplyNew.preUpdate();
        num=num*dao.update(prescriptionApplyNew);



        return num+"";
    }

    /**
     * 住院处方查询
     * @param visitId
     * @return
     * @author 赵宁
     */
    public Page<PrescriptionApply> prescInfoSearch(Page<PrescriptionApply> page,PrescriptionApply prescriptionApply ,String visitId){
        prescriptionApply.setPage(page);
        return page.setList(dao.prescInfoSearch(visitId));
    }

    /**
     * 住院处方保存医嘱
     * @param applyId
     * @return
     */
    @Transactional(readOnly = false)
    public int savePrerscriptitonIn(String applyId,String ordersFlag){
        int num = 0;
        PrescriptionItem prescriptionItem = new PrescriptionItem();
        prescriptionItem.setApplyId(applyId);
        PrescriptionApply prescriptionApply=prescriptionApplyDao.get(applyId);
        PatVisit patVisit=patVisitDao.get(prescriptionApply.getVisitId());
        List<PrescriptionItem> prescriptionItemList = prescriptionItemDao.getPreItem(prescriptionItem);
        if(!"2".equals(ordersFlag)){
            for(PrescriptionItem p:prescriptionItemList){
                Orders saveData = new Orders();
                saveData.setApplyId(applyId);
                saveData.setOrderText(p.getDrugName());
                saveData.setOrderClass("A");
                saveData.setClinicItemId(p.getPriceId());
                saveData.setBillingAttr("0");
                saveData.setOrderStatus("1");//传输状态
                saveData.setWardCode(patVisit.getWardCode());
                saveData.setPatientId(patVisit.getPatientId());
                saveData.setPerformedBy(prescriptionApply.getImplementDept());
                saveData.setVisitId(patVisit.getId());
                saveData.setRepeatIncaditor(ordersFlag);
                saveData.setAdministration(p.getChannel());
                saveData.setSingleDose(p.getSingleDosage());
                saveData.setDoseUnits(p.getSingleUnit());
                saveData.setPerformFreq(p.getFrequency());
                saveData.setDrugSpec(p.getPackageSpec());
                saveData.setFirmId(p.getFirmId());
                saveData.setIsApply("1");
                saveData.setNewDept(patVisit.getWardCode());
                saveData.setCreateDate(new Date());
                saveData.preInsert();
                saveData.updateOrgId();
                num+=ordersDao.insert(saveData);
            }
        }

/**
 * 更改处方申请表状态
 */
        prescriptionApply.setPrescStatus(Global.YES);
        prescriptionApply.preUpdate();
        num = prescriptionApplyDao.update(prescriptionApply);
        return num;
    }



    /**
     * 退费
     * @param prescriptionApply
     * @return
     */
    @Transactional(readOnly = false)
    public int refundIng(PrescriptionApply prescriptionApply){
        int num = dao.refundIng(prescriptionApply);
        return num;
    }

    public List<PrescriptionApply> selectHistory(String patientId){
        return dao.selectHistory(patientId);
    }

    /**
     * 护士端--处方未尽项目查询
     * @param visitId
     * @return
     * @author 赵宁
     */
    public List<PrescriptionApply> prescInfoUnfinished(String visitId){
        return prescriptionApplyDao.prescInfoUnfinished(visitId);
    }

    /**
     * 护士端-处方汇总列表查询
     * @param page
     * @param prescriptionApply
     * @return CTQ
     */
    public Page<BaseDto> findApplyPage(Page<BaseDto> page, PrescriptionApply prescriptionApply) {
        prescriptionApply.updateOrgId();
        prescriptionApply.setWardCode(UserUtils.getUser().getOrgDept().getId());
        List<BaseDto> baseDtoList = prescriptionApplyDao.prescNursesTimePrint(prescriptionApply);
        page.setList(baseDtoList);
        page.setCount(baseDtoList.size());
        return page;
    }

    /**
     * 护理端 按科室查询处方单汇总打印
     * @param prescriptionApply
     * @return
     * @author CTQ
     */
    public String printPrescNurses(PrescriptionApply prescriptionApply){
        String printPath = "";
        User user = UserUtils.getUser();
        String orderedBy = orgDeptDao.get(user.getOrgDept().getId()).getDeptName();//护理单元
        Map map =new HashMap();
        map.put("orderedBy",orderedBy);
        if(StringUtils.isNotBlank(prescriptionApply.getStartTime()) && StringUtils.isNotBlank(prescriptionApply.getEndTime())){
            map.put("time",prescriptionApply.getStartTime());
            map.put("endTime",prescriptionApply.getEndTime());
        }else {
            map.put("time","");
            map.put("endTime","");
        }
        prescriptionApply.updateOrgId();
        prescriptionApply.setWardCode(user.getOrgDept().getId());
        List<BaseDto> baseDtoList = prescriptionApplyDao.prescNursesTimePrint(prescriptionApply);
        if(baseDtoList.size()<1){
            printPath = "暂无数据";
        }else {
            printPath = PrintPdfUtils.previewPdf("nurse", "his/nurse/presc/PrescNurses.jasper", map, baseDtoList, "PrescNurses");
        }

        return printPath;
    }


    /**
     * 门诊处方打印
     * @param applyId
     * @param applyOn
     * @return
     */
    public String printPresc(String applyId, String applyOn,String clinicId,String patientId,String visitId) {
        PrescriptionApply prescriptionApply1= prescriptionApplyDao.getPrintInfo(applyId,applyOn);
        List<PrescriptionItem> list = prescriptionItemDao.findList(new PrescriptionItem(applyId));
        UserUtils userUtils = new UserUtils();
        ClinicMaster clinicMaster = new ClinicMaster();
        Map map =new HashMap();
        HisDiagnosis hisDiagnosis = new HisDiagnosis();
        String url="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd ");
        String hospital = companyDao.get(userUtils.getUser().getOrgId()).getOrgName();
        if(!"".equals(clinicId) && clinicId != null){
            clinicMaster = clinicMasterDao.getPrintInfo(patientId);
            String sex =clinicMaster.getSex();
            map.put("sex",sex);
            map.put("age",clinicMaster.getAge());
            map.put("clinicNo",clinicMaster.getClinicNo());
            map.put("name",clinicMaster.getName());//患者姓名
            map.put("visitDate", sdf.format(clinicMaster.getVisitDate()));//就诊时间
            hisDiagnosis.setClinicId(clinicId);
            map.put("type","门诊");
        } else {
            PatVisit patVisit = patVisitDao.getPrintInfo(visitId);
            map.put("inpNo",patVisit.getVisitNo());
            map.put("bedNo",patVisit.getBedNo());
            map.put("name",patVisit.getPatVisitIndex().getName());//患者姓名
            map.put("sex",patVisit.getPatVisitIndex().getSex());
            map.put("age",patVisit.getPatVisitIndex().getAge());
            hisDiagnosis.setVisitId(visitId);
            map.put("type","住院");
        }

        String hisDiagnosi = "";
        List<HisDiagnosis> list1 = hisDiagnosisDao.findList(hisDiagnosis);
        for(int i=0;i<list1.size();i++){
            hisDiagnosi+= list1.get(i).getIcdName()+",";
        }
        List<BaseDto> baseDtoList = prescriptionApplyDao.getOutpPrescPrint(userUtils.getUser().getOrgId(),clinicId,applyId,applyOn,visitId);
        if(baseDtoList.size()>0){
            String userName =baseDtoList.get(0).getAsString("userName");
            map.put("userName",userName);//医师
        }
        Double costs = 0.00;
        for(int i = 0;i<baseDtoList.size();i++){
            costs+=baseDtoList.get(i).getAsInteger("costs");
        }
        map.put("charges",costs);
        map.put("hospital", hospital);//机构名
        map.put("examine","");//审核人
        map.put("drug","");//发药人
        map.put("chubuzhenduan",hisDiagnosi);//临床诊断

        map.put("date", sdf.format(new Date()));//打印日期
        String dispensaryss =baseDtoList.get(0).getAsString("dispensary");
        if("".equals(dispensaryss)){
            map.put("dispensary","");//取药药房
        }else {
            String dispensary = drugStorageDeptDao.get(dispensaryss).getStorageName();
            map.put("dispensary",dispensary);//取药药房
        }
        map.put("Id",baseDtoList.get(0).getAsString("prescNo"));//处方号
        map.put("deptName",baseDtoList.get(0).getAsString("billingDept"));//就诊科室
        map.put("repetition",baseDtoList.get(0).getAsString("repetition"));
        map.put("frequency",baseDtoList.get(0).getAsString("frequency"));
        map.put("administration",baseDtoList.get(0).getAsString("administration"));
        if("1".equals(prescriptionApply1.getPrescAttr())){
            map.put("prescAttr","普");
        } else if("2".equals(prescriptionApply1.getPrescAttr())){
            map.put("prescAttr","麻");
        } else if("3".equals(prescriptionApply1.getPrescAttr())){
            map.put("prescAttr","毒");
        } else {
            map.put("prescAttr","精");
        }
        String printPath="";
        String classItem="A";
        if(baseDtoList.size()>0){
            classItem=baseDtoList.get(0).getAsString("itemclass");
        }
        if("A".equals(classItem)){
            printPath = PrintPdfUtils.previewPdf(userUtils.getUser().getId(), "his/outpPresc/prescriptionList.jasper", map, baseDtoList, "outpPresc");
        }else{
            printPath = PrintPdfUtils.previewPdf(userUtils.getUser().getId(), "his/outpPresc/chineseMedicine.jasper", map, baseDtoList, "outpPresc");
        }
        return printPath;
    }

    /**
     * 保存模板
     * @param applyId
     * @return
     */

    @Transactional(readOnly = false)
    public int buildTemplate(String applyId) {
        String fTreatId = "";
        String fId = "";
        int num = 0;
        prescriptionApplyDao.updateIsTemplate(applyId,"1");
        PrescriptionItem prescriptionItem = new PrescriptionItem();
        prescriptionItem.setApplyId(applyId);
        List<PrescriptionItem> list = prescriptionItemDao.getPreItem(prescriptionItem);
        PrescriptionApply prescriptionApply = prescriptionApplyDao.get(applyId);
        DoctorTempla doctorTempla = new DoctorTempla();
        doctorTempla.preInsert();
        doctorTempla.updateOrgId();
        doctorTempla.setDeptCode(UserUtils.getUser().getOrgDept().getId());
        doctorTempla.setCreatr(UserUtils.getUser().getId());
        doctorTempla.setDelFlag("0");
        doctorTempla.setProjectType("2");
        doctorTempla.setItemClass("A");
        doctorTempla.setFlag("1");
        doctorTempla.setBillingDept(prescriptionApply.getBillingDept());
        doctorTempla.setImplementDept(prescriptionApply.getImplementDept());
        doctorTemplaDao.insert(doctorTempla);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                PrescriptionItem prescriptionItem1 = list.get(i);
                TreatProjectItem treatProjectItem = new TreatProjectItem(new TreatProjectItem());
                if (StringUtils.isBlank(prescriptionItem1.getParent().getId())) {
                    treatProjectItem.preInsert();
                    fId = treatProjectItem.getId();
                    fTreatId = prescriptionItem1.getId();
                    treatProjectItem.getParent().setId("");
                } else {
                    if (prescriptionItem1.getParent().getId().equals(fTreatId)) {
                        treatProjectItem.preInsert();
                        treatProjectItem.getParent().setId(fId);
                    } else {
                        treatProjectItem.preInsert();
                        treatProjectItem.getParent().setId("");
                    }
                }
                treatProjectItem.setApplyId(doctorTempla.getId());
                treatProjectItem.setOrderCode(prescriptionItem1.getDrugCode());
                treatProjectItem.setOrderText(prescriptionItem1.getDrugName());
                treatProjectItem.setOrderClass("A");
                treatProjectItem.setAmount(prescriptionItem1.getNum().toString());
                treatProjectItem.setSingleDose(prescriptionItem1.getSingleDosage().toString());
                treatProjectItem.setSingleDoseUnit(prescriptionItem1.getSingleUnit());
                treatProjectItem.setPerformFreq(prescriptionItem1.getFrequency());
                treatProjectItem.setAdministration(prescriptionItem1.getChannel());
                treatProjectItem.setFirmId(prescriptionItem1.getFirmId());
                treatProjectItem.setFirmName(prescriptionItem1.getFirmName());
                treatProjectItem.setDrugUnits(prescriptionItem1.getPackageUnit());
                treatProjectItem.setPerformedBy(prescriptionApply.getImplementDept());
                treatProjectItem.setNewDept(prescriptionApply.getBillingDept());
                treatProjectItem.setPrice(prescriptionItem1.getPrice().toString());
                treatProjectItem.setSumPrice(prescriptionItem1.getSumPrice().toString());
                treatProjectItem.setPackageSpec(prescriptionItem1.getPackageSpec());
                treatProjectItem.setPriceId(prescriptionItem1.getPriceId());
                num += treatProjectItemDao.insert(treatProjectItem);
            }
        }
        return num;
    }


    @Transactional(readOnly = false)
    public int retAmount(PrescriptionApply prescriptionApply) {
        int num  = dao.retAmountInp(prescriptionApply.getId(),"5");
        return num;
    }

    public void saveChinaTem(TreatProjectItem treatProjectItem) {


    }
}